import React, {Component} from 'react'
import {Button, Input, message, Spin, Table} from "antd"
import {RootState} from '../../../../reducers/index'
import {connect, ConnectedProps} from 'react-redux'
import ButtonGroup from 'antd/lib/button/button-group'
import ManufacturerInfo from "../../../../types/ManufacturerInfo";
import {
    listManufacturer,
    listManufacturerOnID,
    queryManufacturerInfoAmount,
    queryManufacturerInfoAmountOnID,
    searchManufacturerNotJoin
} from "../../../../requests/Manufacturer";
import {getRes} from '../../../../configFile'
import JoinManufacturerModal from "./JoinManufacturerModal";


interface PropsFromRedux extends ConnectedProps<typeof connector> { }
interface IState {
    ManufacturerSource: Array<ManufacturerInfo & { key: number }>       //显示信息
    amount: number                                                          //总共条目
    offset: number                                                          //偏移量
    limit: number                                                           //条数
    isLoading: boolean                                                       //是否加载中
    modifyModalVisible: boolean,                                             //编辑的模态框是否为显示状态
    isSearch: boolean
}
const { Search } = Input;
class UserJoinManufacturer extends Component<PropsFromRedux, IState> {
    constructor(props: PropsFromRedux) {
        super(props)
        this.state = {
            ManufacturerSource: [],
            amount: 0,
            offset: 0,
            limit: 10,
            isLoading: true,
            modifyModalVisible: false,
            isSearch: false
        }
    }


    //加入厂商
    joinManufacturer = (manufacturerID: number, manufacturerName: string, refresh: () => void) => {
        JoinManufacturerModal(manufacturerID, manufacturerName, refresh)
    }

    getDifferentArr = (allArr: Array<ManufacturerInfo>, partArr: Array<ManufacturerInfo>) => {
        for (let i = allArr.length - 1; i >= 0; i--) {
            for (let j = 0; j < partArr.length; j++) {
                if (allArr[i].manufacturerID === partArr[j].manufacturerID) {
                    allArr.splice(i, 1);
                    break;
                }
            }
        }
        return allArr;
    }

    //获取厂商数据
    getManufacturer = async () => {
        try {
            this.setState({
                ...this.state,
                isLoading: true
            })
            const amountPartRes = getRes(await queryManufacturerInfoAmountOnID(this.props.userID))
            const amountAllRes = getRes(await queryManufacturerInfoAmount())
            const partRes = getRes(await listManufacturerOnID(this.state.offset, this.state.limit, this.props.userID))
            const allRes = getRes(await listManufacturer(this.state.offset, this.state.limit))
            const resultAmount = amountAllRes.data - amountPartRes.data
            const resultRes = this.getDifferentArr(allRes.data, partRes.data)
            console.log(resultRes)
            console.log(resultAmount)
            this.setState({
                ManufacturerSource: resultRes.map((item: ManufacturerInfo) => Object.assign({}, item, { key: item.manufacturerID })),
                amount: resultAmount
            })
        }
        catch (error) {
            message.error(error.toString())
        }
        finally {
            this.setState({
                ...this.state,
                isLoading: false
            })
        }
    }

    componentDidMount() {
        this.getManufacturer()
    }

    columns = [{
        title: '厂商名称',
        dataIndex: 'manufacturerName',
        key: 'manufacturerName',
    },
    {
        title: '厂商联系电话',
        dataIndex: 'manufacturerTelephone',
        key: 'manufacturerTelephone',
    },

    {
        title: '操作',
        key: 'action',
        render: (record: ManufacturerInfo) => (
            <ButtonGroup>
                <Button size='middle'  onClick={this.joinManufacturer.bind(this, record.manufacturerID, record.manufacturerName, this.getManufacturer)}>加入</Button>
            </ButtonGroup>
        )
    }]

    onSearch: (values: string) => void = async values => {
        console.log(values)
        if(values===''){
            await this.getManufacturer()
        }else{
            try {
                const res = getRes(await searchManufacturerNotJoin(values))
                if (res.isSuccessful) {
                    this.setState({ ManufacturerSource: res.data, amount: res.data.length, isSearch: true })
                } else {
                    console.error(res);
                    message.error("查询失败")
                }
            } catch (err) {
                message.error(JSON.stringify(err))
            }
        }
    }
    render() {
        return (
            <div>
                <Spin spinning={this.state.isLoading}>
                    <Search placeholder="搜索" onSearch={values => this.onSearch(values)} allowClear={true} enterButton />
                    <Table columns={this.columns}
                        dataSource={this.state.ManufacturerSource}
                        pagination={{
                            onChange: this.state.isSearch ? undefined : (page, pageSize) => {
                                console.log(page, pageSize);
                                if (!!pageSize) {
                                    this.setState({
                                        offset: (page - 1) * (pageSize),
                                        limit: (pageSize)
                                    },()=>{
                                        this.getManufacturer()
                                    })
                                } else {
                                    console.error('pageSize == undefined')
                                }
                            },
                            defaultPageSize: this.state.limit,
                            total: this.state.amount,
                            showSizeChanger: false
                        }} />
                </Spin>

            </div>
        )
    }
}

//connect加入props
const mapStateToProps = (state: RootState) => {
    return {
        userID: state.loginReducers.userID
    }
}

const connector = connect(mapStateToProps)
export default connector(UserJoinManufacturer)